package com.job51.hro.exlog.interceptor;

import com.job51.hro.exlog.aspect.BaseAspect;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.MDC;

import java.lang.reflect.Method;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author pengfei.ma
 * @create 2023/6/8
 * @since 1.0.0
 */
@Intercepts({
        @Signature(type = Executor.class,method = "query",args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
        @Signature(type = Executor.class,method = "update",args = {MappedStatement.class, Object.class})
})
public class MapperInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        // 获取方法名称
        Object[] args = invocation.getArgs();
        MappedStatement mappedStatement = (MappedStatement) args[0];
        String methodName = getMapperMethodName(mappedStatement);
        MDC.put(BaseAspect.MapperFunction, methodName);
        Object res = invocation.proceed();
        MDC.remove(BaseAspect.MapperFunction);
        return res;
    }


    private String getMapperMethodName(MappedStatement mappedStatement) throws NoSuchMethodException, ClassNotFoundException {
        String id = mappedStatement.getId();
        String mapperClassName = id.substring(0, id.lastIndexOf('.'));
        String mapperMethodName = id.substring(id.lastIndexOf('.') + 1);

        Class<?> mapperClass = Class.forName(mapperClassName);
        Method[] methods = mapperClass.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(mapperMethodName)) {
                return method.getName();
            }
        }

        return "";
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }
}
